// 全局变量
let currentPage = 1;
const pageSize = 10;
let totalNotes = 0;

// 置顶笔记相关全局变量
let currentPinnedPage = 1;
const pinnedPageSize = 3;
let totalPinnedNotes = 0;

// 查询条件全局变量
let searchParams = {
  title: '',
  type: '',
  source: '',
  content: '',
  think: ''
};



// 打开复习笔记页面
function openReviewPage() {
  console.log('复习笔记按钮被点击');
  
  try {
    // 尝试使用扩展的URL格式
    const extensionId = chrome.runtime.id;
    const reviewPageUrl = `chrome-extension://${extensionId}/review.html`;
    console.log('尝试打开URL:', reviewPageUrl);
    window.open(reviewPageUrl, '_blank');
  } catch (error) {
    console.error('使用扩展URL失败:', error);
    
    // 备用方案：尝试使用相对路径
    try {
      console.log('尝试使用相对路径打开页面');
      window.open('./review.html', '_blank');
    } catch (error2) {
      console.error('相对路径也失败:', error2);
      
      // 最后的备用方案：使用绝对路径
      try {
        const currentUrl = window.location.href;
        const baseUrl = currentUrl.substring(0, currentUrl.lastIndexOf('/') + 1);
        const reviewPageUrl = baseUrl + 'review.html';
        console.log('尝试使用绝对路径:', reviewPageUrl);
        window.open(reviewPageUrl, '_blank');
      } catch (error3) {
        console.error('所有方法都失败:', error3);
        alert('无法打开复习页面，请检查扩展配置');
      }
    }
  }
}

// 打开复习笔记页面并指定笔记ID
async function openReviewPageWithNote(noteId) {
  console.log('复习指定笔记按钮被点击，笔记ID:', noteId);
  
  try {
    // 先验证笔记是否存在
    const response = await fetch(`http://127.0.0.1:3000/api/notes/${noteId}/detail`);
    const result = await response.json();
    
    if (!result.success) {
      alert('笔记不存在或获取失败：' + result.message);
      return;
    }
    
    // 构建带参数的复习页面URL
    const reviewPageUrl = `./review.html?noteId=${encodeURIComponent(noteId)}`;
    console.log('打开复习页面URL:', reviewPageUrl);
    
    // 打开复习页面
    try {
      const extensionId = chrome.runtime.id;
      const fullReviewPageUrl = `chrome-extension://${extensionId}/review.html?noteId=${encodeURIComponent(noteId)}`;
      console.log('尝试打开扩展URL:', fullReviewPageUrl);
      window.open(fullReviewPageUrl, '_blank');
    } catch (error) {
      console.error('使用扩展URL失败:', error);
      
      try {
        console.log('尝试使用相对路径打开页面');
        window.open(reviewPageUrl, '_blank');
      } catch (error2) {
        console.error('相对路径也失败:', error2);
        
        try {
          const currentUrl = window.location.href;
          const baseUrl = currentUrl.substring(0, currentUrl.lastIndexOf('/') + 1);
          const absoluteReviewPageUrl = baseUrl + 'review.html?noteId=' + encodeURIComponent(noteId);
          console.log('尝试使用绝对路径:', absoluteReviewPageUrl);
          window.open(absoluteReviewPageUrl, '_blank');
        } catch (error3) {
          console.error('所有方法都失败:', error3);
          alert('无法打开复习页面，请检查扩展配置');
        }
      }
    }
  } catch (error) {
    console.error('验证笔记时出错:', error);
    alert('验证笔记失败：' + error.message);
  }
}



// 获取总数
async function fetchNoteCount() {
  try {
    const params = new URLSearchParams({ ...searchParams });
    const response = await fetch('http://127.0.0.1:3000/api/notes/count?' + params.toString());
    const result = await response.json();
    if (result.success) {
      totalNotes = result.total;
    } else {
      totalNotes = 0;
    }
  } catch (e) {
    totalNotes = 0;
  }
}

// 获取置顶笔记总数
async function fetchPinnedNoteCount() {
  try {
    const response = await fetch('http://127.0.0.1:3000/api/notes/pinned/count');
    const result = await response.json();
    if (result.success) {
      totalPinnedNotes = result.total;
    } else {
      totalPinnedNotes = 0;
    }
  } catch (e) {
    totalPinnedNotes = 0;
  }
}

// 渲染分页栏
function renderPagination() {
  const pagination = document.getElementById('pagination');
  const totalPages = Math.ceil(totalNotes / pageSize) || 1;
  let html = '';
  if (totalPages <= 1) {
    pagination.innerHTML = '';
    return;
  }
  html += `<button ${currentPage === 1 ? 'disabled' : ''} data-page="${currentPage - 1}">←</button>`;
  // 页码区间
  let pageArr = [];
  if (totalPages <= 10) {
    for (let i = 1; i <= totalPages; i++) pageArr.push(i);
  } else {
    if (currentPage <= 5) {
      pageArr = [1,2,3,4,5,6,'...',totalPages];
    } else if (currentPage >= totalPages - 4) {
      pageArr = [1,'...',totalPages-5,totalPages-4,totalPages-3,totalPages-2,totalPages-1,totalPages];
    } else {
      pageArr = [1,'...',currentPage-2,currentPage-1,currentPage,currentPage+1,currentPage+2,'...',totalPages];
    }
  }
  for (let p of pageArr) {
    if (p === '...') {
      html += `<span style='padding:0 4px;'>...</span>`;
    } else {
      html += `<button class="${p === currentPage ? 'active-page' : ''}" ${p === currentPage ? 'disabled' : ''} data-page="${p}">${p}</button>`;
    }
  }
  html += `<button ${currentPage === totalPages ? 'disabled' : ''} data-page="${currentPage + 1}">→</button>`;
  pagination.innerHTML = html;
  
  // 绑定分页按钮事件
  pagination.querySelectorAll('button').forEach(btn => {
    btn.addEventListener('click', async function() {
      const page = parseInt(this.getAttribute('data-page'));
      if (!isNaN(page) && !this.disabled) {
        await gotoPage(page);
      }
    });
  });
}

// 跳转页
async function gotoPage(page) {
  if (page < 1) page = 1;
  const totalPages = Math.ceil(totalNotes / pageSize) || 1;
  if (page > totalPages) page = totalPages;
  currentPage = page;
  await loadNoteList();
}

// 获取并渲染笔记列表（分页）
async function loadNoteList() {
  // 同时加载置顶笔记和普通笔记
  await loadPinnedNoteList();
  
  const tableBody = document.getElementById('noteTableBody');
  tableBody.innerHTML = '<tr><td colspan="7" style="text-align:center;color:#aaa;">加载中...</td></tr>';
  await fetchNoteCount();
  try {
    const params = new URLSearchParams({ ...searchParams, page: currentPage, pageSize });
    const response = await fetch(`http://127.0.0.1:3000/api/notes?${params.toString()}`);
    const result = await response.json();
    if (result.success && Array.isArray(result.data)) {
      if (result.data.length === 0) {
        tableBody.innerHTML = '<tr><td colspan="8" style="text-align:center;color:#aaa;">暂无笔记</td></tr>';
        renderPagination();
        return;
      }
      tableBody.innerHTML = result.data.map(note => `
        <tr>
          <td>${note['主键']}</td>
          <td>${note['标题']}</td>
          <td>${note['类型']}</td>
          <td>${note['关键词']}</td>
          <td>${note['来源'] || ''}</td>
          <td>${note['创建时间'] ? note['创建时间'].replace('T', ' ').slice(0, 19) : ''}</td>
          <td style='white-space:nowrap;'>
            <span style='display:inline-flex;gap:4px;'>
              <button class='detail-btn' data-id='${note['主键']}'>查看详情</button>
              <button class='edit-btn' data-id='${note['主键']}'>修改</button>
              <button class='review-single-btn' data-id='${note['主键']}'>复习</button>
              <button class='pin-btn' data-id='${note['主键']}'>📌</button>
              <button class='delete-btn' data-id='${note['主键']}'>删除</button>
            </span>
          </td>
        </tr>
      `).join('');
      renderPagination();
      // 绑定详情按钮事件
      document.querySelectorAll('#noteTableBody .detail-btn').forEach(btn => {
        btn.onclick = async function() {
          const id = this.getAttribute('data-id');
          await showNoteDetail(id, this);
        };
      });
      // 绑定修改按钮事件
      document.querySelectorAll('#noteTableBody .edit-btn').forEach(btn => {
        btn.onclick = async function() {
          const id = this.getAttribute('data-id');
          await showEditModal(id);
        };
      });
      // 绑定删除按钮事件
      document.querySelectorAll('#noteTableBody .delete-btn').forEach(btn => {
        btn.onclick = async function() {
          const id = this.getAttribute('data-id');
          if (confirm('确定要删除该笔记吗？此操作不可恢复！')) {
            await deleteNote(id);
          }
        };
      });
      
      // 绑定复习按钮事件
      document.querySelectorAll('#noteTableBody .review-single-btn').forEach(btn => {
        btn.onclick = async function() {
          const id = this.getAttribute('data-id');
          await openReviewPageWithNote(id);
        };
      });
      
      // 绑定置顶按钮事件
      document.querySelectorAll('#noteTableBody .pin-btn').forEach(btn => {
        btn.onclick = async function() {
          const id = this.getAttribute('data-id');
          if (confirm('确定要置顶该笔记吗？')) {
            await pinNote(id);
          }
        };
      });
    } else {
      tableBody.innerHTML = '<tr><td colspan="8" style="text-align:center;color:#f00;">加载失败</td></tr>';
      renderPagination();
    }
  } catch (e) {
    tableBody.innerHTML = '<tr><td colspan="8" style="text-align:center;color:#f00;">服务未启动或网络错误</td></tr>';
    renderPagination();
  }
}

// 查看详情展开/收起
async function showNoteDetail(id, btn) {
  const tr = btn.closest('tr');
  // 如果已展开，收起
  if (tr.nextElementSibling && tr.nextElementSibling.classList.contains('detail-row')) {
    tr.nextElementSibling.remove();
    btn.textContent = '查看详情';
    return;
  }
  // 收起其他已展开的详情
  document.querySelectorAll('.detail-row').forEach(row => row.remove());
  document.querySelectorAll('.detail-btn').forEach(b => b.textContent = '查看详情');
  btn.textContent = '收起';
  // 加载详情
  let html = `<td colspan="7" style="background:#f9f9f9;color:#333;"><span style='color:#888;'>加载中...</span></td>`;
  const detailTr = document.createElement('tr');
  detailTr.className = 'detail-row';
  detailTr.innerHTML = html;
  tr.parentNode.insertBefore(detailTr, tr.nextSibling);
  try {
    const response = await fetch(`http://127.0.0.1:3000/api/notes/${id}/detail`);
    const result = await response.json();
    if (result.success) {
      const content = result.data['内容'] || '';
      const think = result.data['思考'] || '';
      // 兼容纯文本和富文本，先将\n替换为<br>
      const safeContent = content ? content.replace(/\n/g, '<br>') : '<span style=\'color:#aaa;\'>无</span>';
      const safeThink = think ? think.replace(/\n/g, '<br>') : '<span style=\'color:#aaa;\'>无</span>';
      html = `<td colspan="7" style="background:#f9f9f9;color:#333;">
        <div style='padding:8px 0 4px 0;'><b>内容：</b><br><div class='rich-content'>${safeContent}</div></div>
        <div style='padding:4px 0 4px 0;'><b>思考：</b><br><div class='rich-content'>${safeThink}</div></div>
      </td>`;
    } else {
      html = `<td colspan="7" style="background:#f9f9f9;color:#f00;">获取详情失败：${result.message}</td>`;
    }
  } catch (e) {
    html = `<td colspan="7" style="background:#f9f9f9;color:#f00;">获取详情失败：${e.message}</td>`;
  }
  detailTr.innerHTML = html;
}

// 编辑弹窗逻辑
async function showEditModal(id) {
  const mask = document.getElementById('editModalMask');
  const form = document.getElementById('editForm');
  mask.style.display = 'flex';
  // 清空表单
  form.reset();
  document.getElementById('editId').value = id;
  // 加载数据
  try {
    const response = await fetch(`http://127.0.0.1:3000/api/notes/${id}/edit`);
    const result = await response.json();
    if (result.success) {
      document.getElementById('editTitle').value = result.data['标题'] || '';
      document.getElementById('editType').value = result.data['类型'] || '';
      document.getElementById('editKeyList').value = result.data['关键词'] || '';
      document.getElementById('editSource').value = result.data['来源'] || '';
      document.getElementById('editContent').value = result.data['内容'] || '';
      document.getElementById('editThink').value = result.data['思考'] || '';
    } else {
      alert('获取数据失败：' + result.message);
      mask.style.display = 'none';
    }
  } catch (e) {
    alert('获取数据失败：' + e.message);
    mask.style.display = 'none';
  }
}

// 关闭弹窗
function closeEditModal() {
  document.getElementById('editModalMask').style.display = 'none';
}

document.getElementById('editCancelBtn').onclick = closeEditModal;
document.getElementById('editModalMask').onclick = function(e) {
  if (e.target === this) closeEditModal();
};

// 提交更新
const editForm = document.getElementById('editForm');
editForm.onsubmit = async function(e) {
  e.preventDefault();
  const id = document.getElementById('editId').value;
  const data = {
    title: document.getElementById('editTitle').value,
    type: document.getElementById('editType').value,
    key_list: document.getElementById('editKeyList').value,
    source: document.getElementById('editSource').value,
    content: document.getElementById('editContent').value,
    think: document.getElementById('editThink').value
  };
  try {
    const response = await fetch(`http://127.0.0.1:3000/api/notes/${id}/edit`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    });
    const result = await response.json();
    if (result.success) {
      alert('更新成功！');
      closeEditModal();
      // 同时刷新置顶笔记和普通笔记列表
      await loadNoteList();
    } else {
      alert('更新失败：' + result.message);
    }
  } catch (e) {
    alert('更新失败：' + e.message);
  }
};

// 获取笔记类型列表
async function fetchNoteTypes() {
  try {
    const response = await fetch('http://127.0.0.1:3000/api/note_types');
    const result = await response.json();
    if (result.success && Array.isArray(result.data)) {
      return result.data;
    }
    return [];
  } catch (e) {
    return [];
  }
}

// 渲染类型下拉框
function renderTypeSelect(selectEl, types, selectedValue) {
  selectEl.innerHTML = '<option value="">请选择类型</option>' +
    types.map(type => `<option value="${type}">${type}</option>`).join('');
  if (selectedValue) selectEl.value = selectedValue;
}

// 初始化类型下拉框
async function initTypeSelects() {
  const types = await fetchNoteTypes();
  const typeSelect = document.getElementById('type');
  const editTypeSelect = document.getElementById('editType');
  if (typeSelect) renderTypeSelect(typeSelect, types);
  if (editTypeSelect) renderTypeSelect(editTypeSelect, types);
}

// 页面加载时初始化类型下拉框
window.addEventListener('DOMContentLoaded', () => {
  initTypeSelects();
});

// 编辑弹窗打开时，动态填充类型选项并选中当前值
async function openEditModal(note) {
  const mask = document.getElementById('editModalMask');
  const form = document.getElementById('editForm');
  mask.style.display = 'flex';
  // 清空表单
  form.reset();
  document.getElementById('editId').value = id;
  // 加载数据
  try {
    const response = await fetch(`http://127.0.0.1:3000/api/notes/${id}/edit`);
    const result = await response.json();
    if (result.success) {
      document.getElementById('editTitle').value = result.data['标题'] || '';
      document.getElementById('editType').value = result.data['类型'] || '';
      document.getElementById('editKeyList').value = result.data['关键词'] || '';
      document.getElementById('editSource').value = result.data['来源'] || '';
      document.getElementById('editContent').value = result.data['内容'] || '';
      document.getElementById('editThink').value = result.data['思考'] || '';
    } else {
      alert('获取数据失败：' + result.message);
      mask.style.display = 'none';
    }
  } catch (e) {
    alert('获取数据失败：' + e.message);
    mask.style.display = 'none';
  }
}

// 页面加载完成后执行
const oldDOMContentLoaded = document.onreadystatechange || function(){};
document.addEventListener('DOMContentLoaded', async function() {
  console.log('DOM加载完成，开始初始化...');
  console.log('当前页面URL:', window.location.href);
  console.log('Chrome API状态:', {
    chrome: typeof chrome,
    runtime: typeof chrome !== 'undefined' ? typeof chrome.runtime : 'undefined',
    getURL: typeof chrome !== 'undefined' && chrome.runtime ? typeof chrome.runtime.getURL : 'undefined'
  });
  
  await loadNoteList();
  if (typeof oldDOMContentLoaded === 'function') oldDOMContentLoaded();
  
  // 绑定复习笔记按钮事件
  const reviewBtn = document.getElementById('reviewBtn');
  if (reviewBtn) {
    console.log('找到复习按钮，绑定事件');
    reviewBtn.addEventListener('click', function(e) {
      console.log('复习按钮被点击');
      e.preventDefault();
      openReviewPage();
    });
  } else {
    console.error('未找到复习按钮');
  }
  
  // 绑定表单提交事件
  document.getElementById('noteForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const formData = {
      title: document.getElementById('title').value,
      type: document.getElementById('type').value,
      keywords: document.getElementById('keywords').value,
      source: document.getElementById('source').value,
      content: document.getElementById('content').value,
      thoughts: document.getElementById('thoughts').value
    };
    
    // 显示加载状态
    const submitBtn = document.getElementById('submitBtn');
    const originalText = submitBtn.textContent;
    submitBtn.textContent = '保存中...';
    submitBtn.disabled = true;
    
    try {
      // 添加调试信息
      console.log('正在发送请求到:', 'http://127.0.0.1:3000/api/notes');
      console.log('请求数据:', formData);
      
      const response = await fetch('http://127.0.0.1:3000/api/notes', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData)
      });
      
      console.log('响应状态:', response.status);
      console.log('响应头:', response.headers);
      
      const result = await response.json();
      
      if (result.success) {
        alert('笔记保存成功！');
        this.reset();
        // 同时刷新置顶笔记和普通笔记列表
        await loadNoteList();
      } else {
        alert('保存失败: ' + result.message);
      }
    } catch (error) {
      console.error('保存笔记时出错:', error);
      console.error('错误详情:', error.message);
      
      // 更详细的错误提示
      let errorMessage = '保存失败: ';
      if (error.name === 'TypeError' && error.message.includes('fetch')) {
        errorMessage += '网络连接失败，请检查：\n1. 后端服务是否启动\n2. 端口3000是否被占用\n3. 防火墙是否阻止连接';
      } else {
        errorMessage += error.message;
      }
      
      alert(errorMessage);
    } finally {
      // 恢复按钮状态
      submitBtn.textContent = originalText;
      submitBtn.disabled = false;
    }
  });

  // 绑定查询表单
  const searchForm = document.getElementById('searchForm');
  if (searchForm) {
    searchForm.onsubmit = async function(e) {
      e.preventDefault();
      searchParams.title = document.getElementById('searchTitle').value.trim();
      searchParams.type = document.getElementById('searchType').value.trim();
      searchParams.source = document.getElementById('searchSource').value.trim();
      searchParams.content = document.getElementById('searchContent').value.trim();
      searchParams.think = document.getElementById('searchThink').value.trim();
      currentPage = 1;
      // 同时刷新置顶笔记和普通笔记列表
      await loadNoteList();
    };
    document.getElementById('resetSearchBtn').onclick = async function() {
      searchParams = { title: '', type: '', source: '', content: '', think: '' };
      document.getElementById('searchTitle').value = '';
      document.getElementById('searchType').value = '';
      document.getElementById('searchSource').value = '';
      document.getElementById('searchContent').value = '';
      document.getElementById('searchThink').value = '';
      currentPage = 1;
      // 同时刷新置顶笔记和普通笔记列表
      await loadNoteList();
    };
  }

  // 最大化/还原编辑弹窗逻辑
  const editModal = document.getElementById('editModal');
  const fullscreenToggleBtn = document.getElementById('fullscreenToggleBtn');
  const fullscreenIcon = document.getElementById('fullscreenIcon');
  let isFullscreen = false;

  if (fullscreenToggleBtn && editModal && fullscreenIcon) {
    fullscreenToggleBtn.addEventListener('click', function(e) {
      e.stopPropagation();
      isFullscreen = !isFullscreen;
      if (isFullscreen) {
        editModal.classList.add('fullscreen-modal');
        fullscreenToggleBtn.title = '还原';
        fullscreenIcon.innerHTML = '<path d="M6 16h2v2h8v-2h2v4H6v-4zm12-8h-2V6H8v2H6V4h12v4z"/>';
      } else {
        editModal.classList.remove('fullscreen-modal');
        fullscreenToggleBtn.title = '最大化';
        fullscreenIcon.innerHTML = '<path d="M4 4h7V2H2v9h2V4zm16 0v7h2V2h-9v2h7zm0 16h-7v2h9v-9h-2v7zM4 20v-7H2v9h9v-2H4z"/>';
      }
    });
  }
});

// 表单提交后刷新笔记列表
const oldSubmit = document.getElementById('noteForm')?.onsubmit || function(){};
document.getElementById('noteForm').addEventListener('submit', async function(e) {
  if (typeof oldSubmit === 'function') oldSubmit(e);
  setTimeout(async () => {
    // 同时刷新置顶笔记和普通笔记列表
    await loadNoteList();
  }, 500); // 延迟刷新，确保后端已写入
});

// 删除笔记
async function deleteNote(id) {
  try {
    const response = await fetch(`http://127.0.0.1:3000/api/notes/${id}/delete`, {
      method: 'DELETE'
    });
    const result = await response.json();
    if (result.success) {
      alert('删除成功！');
      // 同时刷新置顶笔记和普通笔记列表
      await loadNoteList();
    } else {
      alert('删除失败：' + result.message);
    }
  } catch (e) {
    alert('删除失败：' + e.message);
  }
}

// 置顶笔记
async function pinNote(id) {
  try {
    const response = await fetch(`http://127.0.0.1:3000/api/notes/${id}/pin`, {
      method: 'POST'
    });
    const result = await response.json();
    if (result.success) {
      alert('笔记已置顶！');
      // 同时刷新置顶笔记和普通笔记列表
      await loadNoteList();
    } else {
      alert('置顶失败：' + result.message);
    }
  } catch (e) {
    alert('置顶失败：' + e.message);
  }
}

// 取消置顶笔记
async function unpinNote(id) {
  try {
    const response = await fetch(`http://127.0.0.1:3000/api/notes/${id}/unpin`, {
      method: 'POST'
    });
    const result = await response.json();
    if (result.success) {
      alert('已取消置顶！');
      // 同时刷新置顶笔记和普通笔记列表
      await loadNoteList();
    } else {
      alert('取消置顶失败：' + result.message);
    }
  } catch (e) {
    alert('取消置顶失败：' + e.message);
  }
}

// 拖拽分隔条功能
function initResizer() {
  const resizer = document.getElementById('resizer');
  const leftPanel = document.querySelector('.note-list');
  const rightPanel = document.querySelector('.form-area');
  
  if (!resizer || !leftPanel || !rightPanel) {
    console.warn('拖拽分隔条元素未找到');
    return;
  }
  
  let isResizing = false;
  let startX;
  let startWidth;
  
  // 加载保存的宽度设置
  const savedWidths = localStorage.getItem('popup_panel_widths');
  if (savedWidths) {
    try {
      const widths = JSON.parse(savedWidths);
      const containerWidth = leftPanel.parentNode.offsetWidth;
      const resizerWidth = resizer.offsetWidth;
      
      console.log('加载保存的面板宽度:', widths);
      console.log('容器宽度:', containerWidth, '分隔条宽度:', resizerWidth);
      
      // 验证宽度是否合理
      if (widths.left >= 300 && widths.left <= containerWidth * 0.8 && 
          widths.left + resizerWidth <= containerWidth) {
        leftPanel.style.width = widths.left + 'px';
        console.log('应用保存的宽度:', widths.left + 'px');
      } else {
        console.log('保存的宽度不合理，使用默认宽度');
        // 清除不合理的设置
        localStorage.removeItem('popup_panel_widths');
      }
    } catch (e) {
      console.log('加载面板宽度设置失败:', e);
      // 清除损坏的设置
      localStorage.removeItem('popup_panel_widths');
    }
  } else {
    console.log('未找到保存的面板宽度设置');
  }
  
  resizer.addEventListener('mousedown', function(e) {
    isResizing = true;
    startX = e.clientX;
    startWidth = leftPanel.offsetWidth;
    
    // 添加拖拽时的样式
    document.body.style.cursor = 'col-resize';
    document.body.style.userSelect = 'none';
    
    e.preventDefault();
  });
  
  document.addEventListener('mousemove', function(e) {
    if (!isResizing) return;
    
    const deltaX = e.clientX - startX;
    const newWidth = startWidth + deltaX;
    
    // 限制最小和最大宽度
    const minWidth = 300; // 左侧面板最小宽度
    const maxWidth = window.innerWidth * 0.8; // 左侧面板最大宽度为窗口的80%
    const constrainedWidth = Math.max(minWidth, Math.min(maxWidth, newWidth));
    
    leftPanel.style.width = constrainedWidth + 'px';
  });
  
  document.addEventListener('mouseup', function() {
    if (isResizing) {
      isResizing = false;
      
      // 恢复样式
      document.body.style.cursor = '';
      document.body.style.userSelect = '';
      
      // 保存宽度设置到本地存储
      const leftWidth = leftPanel.offsetWidth;
      const widthData = { left: leftWidth };
      localStorage.setItem('popup_panel_widths', JSON.stringify(widthData));
      console.log('保存面板宽度:', widthData);
    }
  });
  
  // 双击重置分隔条位置
  resizer.addEventListener('dblclick', function() {
    leftPanel.style.width = '75%';
    // 保存重置后的宽度
    const resetWidth = leftPanel.offsetWidth;
    const widthData = { left: resetWidth };
    localStorage.setItem('popup_panel_widths', JSON.stringify(widthData));
    console.log('重置并保存面板宽度:', widthData);
  });
  
  // 添加快捷键支持：Ctrl+R 重置面板宽度
  document.addEventListener('keydown', function(e) {
    if (e.ctrlKey && e.key === 'r') {
      e.preventDefault();
      leftPanel.style.width = '75%';
      const resetWidth = leftPanel.offsetWidth;
      const widthData = { left: resetWidth };
      localStorage.setItem('popup_panel_widths', JSON.stringify(widthData));
      console.log('快捷键重置并保存面板宽度:', widthData);
    }
  });
}

// 清除面板宽度设置（用于调试或重置）
function clearPanelWidthSettings() {
  localStorage.removeItem('popup_panel_widths');
  console.log('已清除面板宽度设置');
  // 重新加载页面以应用默认设置
  location.reload();
}

// 在页面加载完成后初始化拖拽功能
document.addEventListener('DOMContentLoaded', function() {
  // 延迟初始化，确保所有元素都已加载
  setTimeout(initResizer, 100);
  
  // 将清除函数添加到全局作用域，方便调试
  window.clearPanelWidthSettings = clearPanelWidthSettings;
});

// 渲染置顶笔记分页栏
function renderPinnedPagination() {
  const pagination = document.getElementById('pinnedPagination');
  const totalPages = Math.ceil(totalPinnedNotes / pinnedPageSize) || 1;
  let html = '';
  if (totalPages <= 1) {
    pagination.innerHTML = '';
    return;
  }
  html += `<button ${currentPinnedPage === 1 ? 'disabled' : ''} data-page="${currentPinnedPage - 1}">←</button>`;
  // 页码区间
  let pageArr = [];
  if (totalPages <= 10) {
    for (let i = 1; i <= totalPages; i++) pageArr.push(i);
  } else {
    if (currentPinnedPage <= 5) {
      pageArr = [1,2,3,4,5,6,'...',totalPages];
    } else if (currentPinnedPage >= totalPages - 4) {
      pageArr = [1,'...',totalPages-5,totalPages-4,totalPages-3,totalPages-2,totalPages-1,totalPages];
    } else {
      pageArr = [1,'...',currentPinnedPage-2,currentPinnedPage-1,currentPinnedPage,currentPinnedPage+1,currentPinnedPage+2,'...',totalPages];
    }
  }
  for (let p of pageArr) {
    if (p === '...') {
      html += `<span style='padding:0 4px;'>...</span>`;
    } else {
      html += `<button class="${p === currentPinnedPage ? 'active-page' : ''}" ${p === currentPinnedPage ? 'disabled' : ''} data-page="${p}">${p}</button>`;
    }
  }
  html += `<button ${currentPinnedPage === totalPages ? 'disabled' : ''} data-page="${currentPinnedPage + 1}">→</button>`;
  pagination.innerHTML = html;
  
  // 绑定分页按钮事件
  pagination.querySelectorAll('button').forEach(btn => {
    btn.addEventListener('click', async function() {
      const page = parseInt(this.getAttribute('data-page'));
      if (!isNaN(page) && !this.disabled) {
        await gotoPinnedPage(page);
      }
    });
  });
}

// 跳转置顶笔记页
async function gotoPinnedPage(page) {
  if (page < 1) page = 1;
  const totalPages = Math.ceil(totalPinnedNotes / pinnedPageSize) || 1;
  if (page > totalPages) page = totalPages;
  currentPinnedPage = page;
  await loadPinnedNoteList();
}

// 获取并渲染置顶笔记列表
async function loadPinnedNoteList() {
  const tableBody = document.getElementById('pinnedNoteTableBody');
  const section = document.getElementById('pinnedNotesSection');
  
  if (!tableBody || !section) {
    console.error('置顶笔记相关元素未找到');
    return;
  }
  
  tableBody.innerHTML = '<tr><td colspan="7" style="text-align:center;color:#aaa;">加载中...</td></tr>';
  await fetchPinnedNoteCount();
  
  // 如果没有置顶笔记，隐藏整个区域
  if (totalPinnedNotes === 0) {
    section.style.display = 'none';
    return;
  }
  
  // 显示置顶笔记区域
  section.style.display = 'block';
  
  try {
    const params = new URLSearchParams({ page: currentPinnedPage, pageSize: pinnedPageSize });
    const response = await fetch(`http://127.0.0.1:3000/api/notes/pinned?${params.toString()}`);
    const result = await response.json();
    if (result.success && Array.isArray(result.data)) {
      if (result.data.length === 0) {
        tableBody.innerHTML = '<tr><td colspan="7" style="text-align:center;color:#aaa;">暂无置顶笔记</td></tr>';
        renderPinnedPagination();
        return;
      }
      tableBody.innerHTML = result.data.map(note => `
        <tr>
          <td>${note['主键']}</td>
          <td>${note['标题']}</td>
          <td>${note['类型']}</td>
          <td>${note['关键词']}</td>
          <td>${note['来源'] || ''}</td>
          <td>${note['创建时间'] ? note['创建时间'].replace('T', ' ').slice(0, 19) : ''}</td>
          <td style='white-space:nowrap;'>
            <span style='display:inline-flex;gap:4px;'>
              <button class='detail-btn' data-id='${note['主键']}' data-pinned='true'>查看详情</button>
              <button class='edit-btn' data-id='${note['主键']}' data-pinned='true'>修改</button>
              <button class='review-single-btn' data-id='${note['主键']}' data-pinned='true'>复习</button>
              <button class='unpin-btn' data-id='${note['主键']}' data-pinned='true'>📌</button>
              <button class='delete-btn' data-id='${note['主键']}' data-pinned='true'>删除</button>
            </span>
          </td>
        </tr>
      `).join('');
      renderPinnedPagination();
      
      // 绑定置顶笔记的按钮事件
      bindPinnedNoteEvents();
    } else {
      tableBody.innerHTML = '<tr><td colspan="7" style="text-align:center;color:#f00;">加载失败</td></tr>';
      renderPinnedPagination();
    }
  } catch (e) {
    tableBody.innerHTML = '<tr><td colspan="7" style="text-align:center;color:#f00;">服务未启动或网络错误</td></tr>';
    renderPinnedPagination();
  }
}

// 绑定置顶笔记的事件
function bindPinnedNoteEvents() {
  // 绑定详情按钮事件
  document.querySelectorAll('#pinnedNoteTableBody .detail-btn').forEach(btn => {
    btn.onclick = async function() {
      const id = this.getAttribute('data-id');
      await showNoteDetail(id, this);
    };
  });
  // 绑定修改按钮事件
  document.querySelectorAll('#pinnedNoteTableBody .edit-btn').forEach(btn => {
    btn.onclick = async function() {
      const id = this.getAttribute('data-id');
      await showEditModal(id);
    };
  });
  // 绑定删除按钮事件
  document.querySelectorAll('#pinnedNoteTableBody .delete-btn').forEach(btn => {
    btn.onclick = async function() {
      const id = this.getAttribute('data-id');
      if (confirm('确定要删除该置顶笔记吗？此操作不可恢复！')) {
        await deleteNote(id);
      }
    };
  });
  
  // 绑定复习按钮事件
  document.querySelectorAll('#pinnedNoteTableBody .review-single-btn').forEach(btn => {
    btn.onclick = async function() {
      const id = this.getAttribute('data-id');
      await openReviewPageWithNote(id);
    };
  });
  
  // 绑定取消置顶按钮事件
  document.querySelectorAll('#pinnedNoteTableBody .unpin-btn').forEach(btn => {
    btn.onclick = async function() {
      const id = this.getAttribute('data-id');
      if (confirm('确定要取消置顶该笔记吗？')) {
        await unpinNote(id);
      }
    };
  });
} 

// 类型管理弹窗逻辑
function showTypeManageModal() {
  document.getElementById('typeManageModalMask').style.display = 'flex';
  loadTypeList();
}
function closeTypeManageModal() {
  document.getElementById('typeManageModalMask').style.display = 'none';
}
// 加载类型列表
async function loadTypeList() {
  const typeListBody = document.getElementById('typeListBody');
  typeListBody.innerHTML = '<tr><td colspan="2" style="text-align:center;color:#aaa;">加载中...</td></tr>';
  const types = await fetchNoteTypes();
  if (!types.length) {
    typeListBody.innerHTML = '<tr><td colspan="2" style="text-align:center;color:#aaa;">暂无类型</td></tr>';
    return;
  }
  typeListBody.innerHTML = types.map(type =>
    `<tr><td>${type}</td><td><button class="delete-type-btn" data-type="${type}" style="color:#d32f2f;background:#ffebee;border:1px solid #ffcdd2;padding:2px 8px;border-radius:3px;cursor:pointer;">删除</button></td></tr>`
  ).join('');
  // 绑定删除事件
  document.querySelectorAll('.delete-type-btn').forEach(btn => {
    btn.onclick = async function() {
      if (confirm('确定要删除类型“' + btn.dataset.type + '”吗？')) {
        await deleteType(btn.dataset.type);
        loadTypeList();
        initTypeSelects(); // 刷新下拉框
      }
    };
  });
}
// 新增类型
async function addType() {
  const input = document.getElementById('newTypeInput');
  const value = input.value.trim();
  if (!value) return alert('请输入类型名称');
  await createType(value);
  input.value = '';
  loadTypeList();
  initTypeSelects(); // 刷新下拉框
}
// 事件绑定
window.addEventListener('DOMContentLoaded', () => {
  document.getElementById('typeManageBtn').onclick = showTypeManageModal;
  document.getElementById('typeManageCloseBtn').onclick = closeTypeManageModal;
  document.getElementById('addTypeBtn').onclick = addType;
});

// 新增类型
async function createType(value) {
  try {
    const response = await fetch('http://127.0.0.1:3000/api/note_types', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ value })
    });
    const result = await response.json();
    if (!result.success) alert('新增类型失败：' + result.message);
  } catch (e) {
    alert('新增类型失败：' + e.message);
  }
}
// 删除类型
async function deleteType(value) {
  try {
    const response = await fetch('http://127.0.0.1:3000/api/note_types/' + encodeURIComponent(value), {
      method: 'DELETE'
    });
    const result = await response.json();
    if (!result.success) alert('删除类型失败：' + result.message);
  } catch (e) {
    alert('删除类型失败：' + e.message);
  }
} 